<template>
  <div>
    <svg-icon icon-class="voiceSet" @click="drawer = true" />
    <el-drawer
      title="播报设置"
      :visible.sync="drawer"
      :direction="direction"
      :modal="false"
      :before-close="handleClose"
      size="380px"
    >
      <div class="voice-drawer-content">
        <!-- 语音总开关 -->
        <div class="setting-group">
          <div class="setting-label">
            <i class="el-icon-switch-button" />
            语音播报
          </div>
          <div class="voice-switch">
            <el-switch
              v-model="voiceEnabled"
              active-text="开启"
              inactive-text="关闭"
              active-color="#409EFF"
              @change="onVoiceSwitchChange"
            />
            <span class="switch-tips">{{ voiceEnabled ? '语音播报已开启' : '语音播报已关闭' }}</span>
          </div>
        </div>

        <!-- 语音选择 -->
        <div class="setting-group">
          <div class="setting-label">
            <i class="el-icon-microphone" />
            选择语音
          </div>
          <el-select
            v-model="selectedVoice"
            placeholder="请选择语音"
            class="voice-select"
            :disabled="!voiceEnabled"
            @change="onVoiceChange"
          >
            <el-option
              v-for="(voice, index) in chineseVoices"
              :key="index"
              :label="voiceDisplayName(voice)"
              :value="index"
            >
              <span class="voice-option">
                <span class="voice-name">{{ voice.name }}</span>
                <span class="voice-lang">{{ formatLanguage(voice.lang) }}</span>
              </span>
            </el-option>
          </el-select>
        </div>

        <!-- 语音参数设置 -->
        <div class="setting-group">
          <div class="setting-label">
            <i class="el-icon-setting" />
            语音参数
          </div>

          <div class="parameter-item">
            <div class="parameter-info">
              <span class="parameter-name">语速</span>
              <span class="parameter-value">{{ formatValue(voiceRate) }}</span>
            </div>
            <el-slider
              v-model="voiceRate"
              :min="0.5"
              :max="2"
              :step="0.1"
              :show-tooltip="true"
              :show-stops="true"
              :format-tooltip="formatTooltip"
              :disabled="!voiceEnabled"
              class="parameter-slider"
            />
          </div>

          <div class="parameter-item">
            <div class="parameter-info">
              <span class="parameter-name">音调</span>
              <span class="parameter-value">{{ formatValue(voicePitch) }}</span>
            </div>
            <el-slider
              v-model="voicePitch"
              :min="0.5"
              :max="2"
              :step="0.1"
              :show-tooltip="true"
              :show-stops="true"
              :format-tooltip="formatTooltip"
              :disabled="!voiceEnabled"
              class="parameter-slider"
            />
          </div>

          <div class="parameter-item">
            <div class="parameter-info">
              <span class="parameter-name">音量</span>
              <span class="parameter-value">{{ formatValue(voiceVolume) }}</span>
            </div>
            <el-slider
              v-model="voiceVolume"
              :min="0"
              :max="1"
              :step="0.1"
              :show-tooltip="true"
              :show-stops="true"
              :format-tooltip="formatTooltip"
              :disabled="!voiceEnabled"
              class="parameter-slider"
            />
          </div>
        </div>

        <!-- 播放控制 -->
        <div class="setting-group">
          <div class="setting-label">
            <i class="el-icon-video-play" />
            播放控制
          </div>
          <div class="control-buttons">
            <el-button
              type="primary"
              :disabled="!voiceEnabled || !hasSelectedVoice || isPlaying"
              class="control-button test-btn"
              @click="testVoice"
            >
              <i class="el-icon-mic" />
              测试语音
            </el-button>
          </div>
        </div>

        <!-- 当前语音状态 -->
        <div class="setting-group status-group">
          <div class="setting-label">
            <i class="el-icon-info" />
            当前状态
          </div>
          <div class="status-info">
            <div class="status-item">
              <span class="status-label">开关:</span>
              <span class="status-value" :class="voiceEnabled ? 'enabled' : 'disabled'">
                <i :class="voiceEnabled ? 'el-icon-check' : 'el-icon-close'" />
                {{ voiceEnabled ? '已开启' : '已关闭' }}
              </span>
            </div>
            <div class="status-item">
              <span class="status-label">语音:</span>
              <span class="status-value">{{ currentVoiceName }}</span>
            </div>
            <div class="status-item">
              <span class="status-label">状态:</span>
              <span class="status-value" :class="{'playing': isPlaying, 'idle': !isPlaying}">
                <i :class="isPlaying ? 'el-icon-loading' : 'el-icon-check'" />
                {{ isPlaying ? '播放中...' : '准备就绪' }}
              </span>
            </div>
            <div v-if="playQueue.length > 0" class="status-item">
              <span class="status-label">队列:</span>
              <span class="status-value">
                {{ playQueue.length }} 条待播报
              </span>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
    <voice-notification ref="voiceNotification" />
  </div>
</template>

<script>
export default {
  name: 'VoiceBroadcast',
  components: {},
  props: {
    // 可以接收默认播报内容
    defaultMessage: {
      type: String,
      default: '您好，这是语音测试，当前语音设置正常。'
    },
    // 是否默认开启语音
    defaultEnabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      drawer: false,
      direction: 'rtl',

      // 语音播报相关数据
      synth: null,
      msg: null,
      voiceList: [],
      chineseVoices: [],
      selectedVoice: null,
      isPlaying: false,
      voiceRate: 1,
      voicePitch: 1,
      voiceVolume: 1,

      // 新增：语音开关
      voiceEnabled: false,

      // 新增：播放队列
      playQueue: [],
      currentPlayIndex: 0
    }
  },
  computed: {
    // 当前选中的语音名称
    currentVoiceName() {
      if (this.selectedVoice !== null && this.chineseVoices[this.selectedVoice]) {
        const voice = this.chineseVoices[this.selectedVoice]
        return `${voice.name} (${this.formatLanguage(voice.lang)})`
      }
      return '未选择'
    },

    // 检查是否有选中的语音
    hasSelectedVoice() {
      return this.selectedVoice !== null && this.chineseVoices[this.selectedVoice]
    }
  },
  watch: {
    // 监听默认消息变化
    defaultMessage: {
      immediate: true,
      handler(newVal) {
        if (newVal && !this.message) {
          this.message = newVal
        }
      }
    },
    // 监听默认开关状态
    defaultEnabled: {
      immediate: true,
      handler(newVal) {
        this.voiceEnabled = newVal
      }
    }
  },
  created() {
    // 初始化语音开关状态
    this.voiceEnabled = this.defaultEnabled
  },
  mounted() {
    // 初始化语音合成
    this.initSpeechSynthesis()
  },
  beforeDestroy() {
    // 停止语音播报
    this.stopVoice()
  },
  methods: {
    // 安全的数值格式化
    formatValue(value) {
      if (value === null || value === undefined) {
        return '1.0'
      }
      return Number(value).toFixed(1)
    },

    // 格式化滑块提示
    formatTooltip(val) {
      return this.formatValue(val)
    },

    // 初始化语音合成
    initSpeechSynthesis() {
      if ('speechSynthesis' in window) {
        this.synth = window.speechSynthesis
        this.msg = new SpeechSynthesisUtterance()

        // 获取语音列表
        this.loadVoices()

        // 监听语音列表变化
        this.synth.onvoiceschanged = () => {
          this.loadVoices()
        }

        // 监听语音播放结束
        this.msg.onend = () => {
          this.isPlaying = false
          // 播放队列中的下一条
          this.playNextInQueue()
        }

        // 监听语音播放错误
        this.msg.onerror = (event) => {
          console.error('语音播放错误:', event)
          this.isPlaying = false
          this.$message.error('语音播放失败，请重试')
          // 即使出错也继续播放下一条
          this.playNextInQueue()
        }
      } else {
        this.$message.warning('您的浏览器不支持语音合成功能')
      }
    },

    // 加载可用语音列表，只保留中文语音
    loadVoices() {
      if (this.synth) {
        try {
          this.voiceList = this.synth.getVoices() || []

          // 过滤出中文语音
          this.chineseVoices = this.voiceList.filter(voice => {
            return voice && voice.lang && (voice.lang.includes('zh') || voice.lang.includes('CN'))
          })

          // 默认选择第一个中文语音
          if (this.chineseVoices.length > 0 && this.selectedVoice === null) {
            this.selectedVoice = 0
          }

          // 如果没有中文语音，给出提示
          if (this.chineseVoices.length === 0) {
            console.warn('未找到中文语音')
            this.$message.warning('未找到中文语音，请检查系统语音设置')
          }
        } catch (error) {
          console.error('加载语音列表失败:', error)
          this.chineseVoices = []
        }
      }
    },

    // 语音显示名称
    voiceDisplayName(voice) {
      if (!voice) return '未知语音'
      return `${voice.name || '未知'} (${this.formatLanguage(voice.lang)})`
    },

    // 格式化语言显示
    formatLanguage(lang) {
      if (!lang) return '未知语言'
      if (lang.includes('zh-CN')) return '简体中文'
      if (lang.includes('zh-TW') || lang.includes('zh-HK')) return '繁体中文'
      if (lang.includes('zh')) return '中文'
      return lang
    },

    // 语音选择变化
    onVoiceChange() {
      console.log('选择的语音:', this.chineseVoices[this.selectedVoice])
    },

    // 语音开关变化
    onVoiceSwitchChange(val) {
      if (!val && this.isPlaying) {
        this.stopVoice()
      }
      this.$emit('voice-enabled-change', val)
    },

    // 播放语音
    playVoice(text) {
      if (!this.synth || !this.msg) {
        this.$message.warning('语音合成未初始化')
        return false
      }

      if (!this.voiceEnabled) {
        console.log('语音播报已关闭，跳过播放')
        return false
      }

      if (!this.hasSelectedVoice) {
        this.$message.warning('请先选择语音')
        return false
      }

      const message = text || '播报内容为空'

      // 停止当前播放
      if (this.isPlaying) {
        this.synth.cancel()
      }

      try {
        // 设置语音参数
        this.msg.text = message
        this.msg.voice = this.chineseVoices[this.selectedVoice]
        this.msg.rate = this.voiceRate || 1
        this.msg.pitch = this.voicePitch || 1
        this.msg.volume = this.voiceVolume || 1

        // 显示播放通知
        // this.showPlayNotification(message)

        // 开始播放
        this.synth.speak(this.msg)
        this.isPlaying = true
        return true
      } catch (error) {
        console.error('播放语音失败:', error)
        this.$voiceNotify.voiceError('播放语音失败: ' + error.message)
        this.isPlaying = false
        return false
      }
    },
    // 显示播放通知
    showPlayNotification(message) {
      // 截短长消息
      // const shortMessage = message.length > 50
      //   ? message.substring(0, 50) + '...'
      //   : message

      // this.$voiceNotify.voiceBroadcast({
      //   title: '正在播报',
      //   message: shortMessage,
      //   type: 'info',
      //   duration: 3000,
      //   showClose: true,
      //   position: 'bottom-left' // 在底部显示，避免干扰主要内容
      // })
    },
    // 外部调用方法：设置播报内容并播放 - 修改方法
    speak(text) {
      if (!this.voiceEnabled) {
        console.log('语音播报已关闭，跳过播放')
        return
      }

      let messages = []
      if (Array.isArray(text)) {
        messages = text.filter(item => item && item.trim())
      } else if (typeof text === 'string' && text.trim()) {
        messages = [text]
      }

      if (messages.length === 0) return

      // 添加到播放队列
      this.playQueue = [...this.playQueue, ...messages]

      // 如果当前没有在播放，开始播放队列
      if (!this.isPlaying) {
        this.playNextInQueue()
      }
    },

    // 停止语音播放
    stopVoice() {
      if (this.synth) {
        this.synth.cancel()
        this.isPlaying = false
        // 清空播放队列
        this.playQueue = []
        this.currentPlayIndex = 0
      }
    },

    // 测试语音（播放简短测试内容）
    testVoice() {
      if (!this.hasSelectedVoice) {
        this.$message.warning('请先选择语音')
        return
      }

      if (!this.voiceEnabled) {
        this.$message.warning('请先开启语音播报')
        return
      }

      this.$voiceNotify.voiceBroadcast({
        title: '测试语音',
        message: '正在播放测试语音...',
        type: 'info',
        duration: 2000,
        position: 'top-center'
      })

      this.playVoice('您好，这是中文语音测试，当前语音设置正常。')
    },

    // 播放队列中的下一条
    playNextInQueue() {
      if (this.playQueue.length > 0) {
        const nextText = this.playQueue.shift()
        if (nextText) {
          // 更新进度通知
          // if (this.progressNotificationId && this.playQueue.length > 0) {
          //   const total = this.playQueue.length + 1 // +1 因为已经移出了一条
          //   const current = total - this.playQueue.length
          //   this.$voiceNotify.updateVoiceProgress(
          //     this.progressNotificationId,
          //     current,
          //     total,
          //     `正在播报第 ${current} 条`
          //   )
          // }

          // 延迟一下再播放下一条，避免连续播放
          setTimeout(() => {
            this.playVoice(nextText)
          }, 500)
        }
      } else {
        // 播放完成，关闭进度通知
        if (this.progressNotificationId) {
          this.$voiceNotify.close(this.progressNotificationId)
          this.progressNotificationId = null
        }
        // this.$voiceNotify.voiceEnd('语音播报完成')
      }
    },

    // 关闭抽屉前的确认
    handleClose(done) {
      // 如果正在播放，先停止
      if (this.isPlaying) {
        this.stopVoice()
      }
      done()
    },

    // 外部调用方法：打开设置面板
    openSettings() {
      this.drawer = true
    },

    // 外部调用方法：设置语音开关状态
    setVoiceEnabled(enabled) {
      this.voiceEnabled = enabled
      if (!enabled) {
        this.stopVoice()
      }
    }
  }
}
</script>

<style scoped lang="scss">
.voice-drawer-content {
  padding: 0 20px 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 24px;

  .setting-group {
    .setting-label {
      font-size: 15px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 12px;
      display: flex;
      align-items: center;

      i {
        margin-right: 8px;
        color: #409EFF;
      }
    }

    .voice-switch {
      display: flex;
      flex-direction: column;
      gap: 8px;

      .switch-tips {
        font-size: 13px;
        color: #909399;
        font-style: italic;
      }
    }

    .voice-select {
      width: 100%;

      ::v-deep .el-input__inner {
        border-radius: 8px;
        height: 40px;
        line-height: 40px;
      }
    }

    .parameter-item {
      margin-bottom: 18px;

      .parameter-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;

        .parameter-name {
          font-size: 14px;
          color: #606266;
        }

        .parameter-value {
          font-weight: 600;
          color: #409EFF;
          font-size: 14px;
          min-width: 30px;
          text-align: right;
        }
      }

      .parameter-slider {
        ::v-deep .el-slider {
          .el-slider__runway {
            height: 6px;
            border-radius: 3px;
            background-color: #EBEEF5;

            .el-slider__bar {
              height: 6px;
              border-radius: 3px;
              background: linear-gradient(90deg, #409EFF, #66b1ff);
            }
          }

          .el-slider__button {
            width: 16px;
            height: 16px;
            border: 2px solid #409EFF;
            background-color: #fff;
            transition: all 0.2s;

            &:hover {
              transform: scale(1.2);
            }
          }

          .el-slider__stop {
            height: 6px;
            width: 6px;
            border-radius: 50%;
            background-color: #C0C4CC;
          }
        }
      }
    }

    .control-buttons {
      display: flex;
      gap: 10px;

      .control-button {
        flex: 1;

        &.test-btn {
          background: #67C23A;
          border-color: #67C23A;
          color: #fff;

          &:hover {
            background: #85ce61;
            border-color: #85ce61;
          }
        }
      }
    }

    &.status-group {
      margin-top: auto;
    }

    .status-info {
      background: #f8f9fa;
      border-radius: 8px;
      padding: 16px;
      border-left: 4px solid #409EFF;

      .status-item {
        display: flex;
        margin-bottom: 10px;

        &:last-child {
          margin-bottom: 0;
        }

        .status-label {
          width: 40px;
          font-size: 13px;
          color: #909399;
        }

        .status-value {
          flex: 1;
          font-size: 13px;
          color: #303133;
          display: flex;
          align-items: center;

          i {
            margin-right: 6px;
          }

          &.enabled {
            color: #67C23A;
            font-weight: 500;
          }

          &.disabled {
            color: #F56C6C;
          }

          &.playing {
            color: #409EFF;
            font-weight: 500;
          }

          &.idle {
            color: #909399;
          }
        }
      }
    }
  }
}

// 语音选项样式
.voice-option {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .voice-name {
    font-weight: 500;
  }

  .voice-lang {
    font-size: 12px;
    color: #909399;
  }
}

// 抽屉标题样式调整
::v-deep .el-drawer__header {
  margin-bottom: 0;
  padding: 20px;
  color: #303133;
  border-bottom: 1px solid #EBEEF5;

  span {
    font-weight: 600;
    font-size: 18px;
  }
}

::v-deep .el-drawer__body {
  padding: 0;
}

// 响应式调整
@media (max-width: 768px) {
  .voice-drawer-content {
    padding: 0 15px 15px;
  }
}
</style>
